package org.znxs.znmanus.tools.webSearch;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
public class SearchApiSearchTool {

    private final String searchApiKey;

    private static final String SEARCH_API_URL = "https://www.searchapi.io/api/v1/search";

    public SearchApiSearchTool(String searchApiKey) {
        this.searchApiKey = searchApiKey;
    }

    @Tool(description = "从searchApi.io引擎搜索内容,如果出现搜索失败，可以尝试多次调用该工具(获取调用其他搜索工具)")
    public String searchApiSearch(@ToolParam(description = "Search query keyword") String query) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("q", query);
        paramMap.put("api_key", searchApiKey);
        paramMap.put("engine", "bing");

        try {
            String response = HttpUtil.get(SEARCH_API_URL, paramMap);
            JSONObject jsonObject = JSONUtil.parseObj(response);
            JSONArray organicResults = jsonObject.getJSONArray("organic_results");

            // 添加日志记录
            log.info("有机搜索结果数量: {}", organicResults == null ? "null" : organicResults.size());

            // 检查organicResults是否为空或者数量不足
            if (organicResults == null || organicResults.isEmpty()) {
                return "没有找到相关结果";
            }

            int sizeToUse = Math.min(organicResults.size(), 5); // 确保不会超出范围
            List<Object> objects = organicResults.subList(0, sizeToUse);

            String result = objects.stream().map(Object::toString).collect(Collectors.joining(","));
            return result;
        } catch (Exception e) {
            return "搜索出错: " + e.getMessage();
        }
    }
}